﻿/***************************************************************************
	Copyright (C) 2010 RapidWebDev Organization (Author: Eunge, Legal Name: Jian Liu, Email: eunge.liu@gmail.com)

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ***************************************************************************/

using System;
using System.Drawing;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using WebGridView = System.Web.UI.WebControls.GridView;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BaoJianSoft.Common;
using BaoJianSoft.Membership;
using BaoJianSoft.Web.Extensions.Controls;
using BaoJianSoft.Web.Extensions.Properties;

namespace BaoJianSoft.Web.Extensions.DynamicPages
{
    /// <summary>
    /// Class to configure gridview control.
    /// </summary>
    public class GridViewPanel : Panel, INamingContainer
    {
        /// <summary>
        /// Get session manager key for current page index.
        /// </summary>
        public const string CURRENT_PAGE_INDEX = "CurrentPageIndex";

        private const string JAVASCRIPT_REGISTRATION = @"
				function OnGirdViewRowMouseOver(row)
		        {
		            var originalClass = $(row).attr(""class"");
		            if (originalClass.indexOf(""mouseover"") < 0)
		                $(row).attr(""class"", originalClass + "" mouseover"");
		        }
		        
		        function OnGirdViewRowMouseOut(row)
		        {
		            var currentClass = $(row).attr(""class"");
		            var originalClass = currentClass.replace(/mouseover/i, """");
		            $(row).attr(""class"", originalClass);
		        }
		        
		        function OnGridViewRowClicked(cell, GridViewRowClickEvent)
		        {
					var row = cell.parentNode;
		            switch(GridViewRowClickEvent)
		            {
		                case ""ClickCheckBox"":
		                    var checkboxSearcher = $("":checkbox"", row);
		                    if (checkboxSearcher.length > 0) 
							{
		                        checkboxSearcher.attr('checked', checkboxSearcher.attr(""checked"") != true);
								checkboxSearcher.change();
							}
		                    break;
		                case ""ClickViewButton"":
		                    var viewButtonSearcher = $("".ViewIconButton"", row);
		                    if (viewButtonSearcher.length > 0) 
		                        eval(viewButtonSearcher.attr(""href""));
		                    break;
		                case ""ClickEditButton"":
		                    var editButtonSearcher = $("".EditIconButton"", row);
		                    if (editButtonSearcher.length > 0) 
	                            eval(editButtonSearcher.attr(""href""));
		                    break;
		            }
		        }";
        private WebGridView gridview;
        private Label labelRecordInfo;
        private Pager pager;
        private bool isPageIndexChanged;

        /// <summary>
        /// Gets hashset values checked primary key fields.
        /// </summary>
        private Collection<string> CheckedPrimaryKeyFieldValues
        {
            get
            {
                Collection<string> results = base.ViewState["CheckedPrimaryKeyFieldValues"] as Collection<string>;
                if (results == null)
                {
                    results = new Collection<string>();
                    base.ViewState["CheckedPrimaryKeyFieldValues"] = results;
                }

                return results;
            }
            set { base.ViewState["CheckedPrimaryKeyFieldValues"] = value; }
        }

        /// <summary>
        /// Set/get predicate to build query criteria.
        /// </summary>
        private string Predicate
        {
            get { return this.ViewState["Predicate"] as string; }
            set { this.ViewState["Predicate"] = value; }
        }

        /// <summary>
        /// Set/get predicate parameters to format query criteria.
        /// </summary>
        private object[] PredicateParameters
        {
            get { return this.ViewState["PredicateParameters"] as object[]; }
            set { this.ViewState["PredicateParameters"] = value; }
        }

        /// <summary>
        /// Set/get query criterias.
        /// </summary>
        private Collection<QueryCriteria> Criterias
        {
            get { return this.ViewState["Criterias"] as Collection<QueryCriteria>; }
            set { this.ViewState["Criterias"] = value; }
        }

        /// <summary>
        /// Gets variables dictionary of control.
        /// </summary>
        protected internal IDictionary<string, object> Variables { get; private set; }

        /// <summary>
        /// Event fires on clicking view button.
        /// </summary>
        public event EventHandler<GridViewPrimaryKeyFieldEventArgs> Viewing;

        /// <summary>
        /// Event fires on clicking edit button.
        /// </summary>
        public event EventHandler<GridViewPrimaryKeyFieldEventArgs> Editing;

        /// <summary>
        /// Event fires on clicking delete button.
        /// </summary>
        public event EventHandler<GridViewPrimaryKeyFieldEventArgs> Deleting;

        /// <summary>
        /// Event fires to authoritize button visibility inside of gridview while binding.
        /// </summary>
        public event EventHandler<GridViewButtonBindingEventArgs> ButtonsBinding;

        /// <summary>
        /// Set/get event handler to loading data source.
        /// </summary>
        public event EventHandler<DataSourceLoadEventArgs> DataSourceLoading;

        /// <summary>
        /// The event fires on binding checkbox in gridview row.
        /// </summary>
        public event EventHandler<GridViewCheckBoxBindingEventArgs> CheckBoxBinding;

        /// <summary>
        /// Set/get gridview building configuration.
        /// </summary>
        public GridViewConfiguration Configuration { get; set; }

        /// <summary>
        /// Sets/gets true to remember selected check box after changing page index.
        /// </summary>
        public bool RememberSelectedCheckBox
        {
            get { if (base.ViewState["RememberSelectedCheckBox"] == null) return false; return (bool)base.ViewState["RememberSelectedCheckBox"]; }
            set { base.ViewState["RememberSelectedCheckBox"] = value; }
        }

        /// <summary>
        /// Get checked collection of entity id.
        /// </summary>
        public ICollection<string> CheckedEntityIds
        {
            get
            {
                if (!this.Configuration.EnabledCheckBoxField)
                {
                    throw new InvalidProgramException(Resources.CheckedEntityIdsNotSupportWhenCheckBoxColumnDisabled);
                }

                Collection<string> checkedPrimaryKeyFieldValues = new Collection<string>();
                foreach (GridViewRow gridViewRow in this.gridview.Rows)
                {
                    CheckBox checkbox = gridViewRow.FindControl("CheckBoxFieldItem") as CheckBox;
                    if (checkbox != null && checkbox.Checked)
                    {
                        string primaryKeyFieldValue = checkbox.Attributes["PrimaryKeyFieldValue"];
                        if (!checkedPrimaryKeyFieldValues.Contains(primaryKeyFieldValue))
                            checkedPrimaryKeyFieldValues.Add(primaryKeyFieldValue);
                    }
                }

                this.CheckedPrimaryKeyFieldValues = new Collection<string>(this.CheckedPrimaryKeyFieldValues.Union(checkedPrimaryKeyFieldValues).Distinct().ToList());
                return this.CheckedPrimaryKeyFieldValues;
            }
        }

        /// <summary>
        /// Get current page index.
        /// </summary>
        public int PageIndex
        {
            get { return this.pager.CurrentPageIndex - 1; }
        }

        /// <summary>
        /// Get dynamic generated grid view control.
        /// </summary>
        public WebGridView GridView { get { return this.gridview; } }

        /// <summary>
        /// Set/get gridview sorting expression. As default, it bases on http session.
        /// </summary>
        protected virtual string SortExpression
        {
            get
            {
                string sessionKey = this.GetSortExpressionSessionKey();
                return HttpContext.Current.Session[sessionKey] as string;
            }
            set
            {
                string sessionKey = this.GetSortExpressionSessionKey();
                HttpContext.Current.Session[sessionKey] = value;
            }
        }

        /// <summary>
        /// Construct GridViewPanel instance.
        /// </summary>
        public GridViewPanel()
        {
            this.Variables = new Dictionary<string, object>();
        }

        /// <summary>
        /// Raises the System.Web.UI.Control.Init event.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            if (this.DataSourceLoading == null)
            {
                throw new InvalidProgramException(string.Format(Resources.EventNotBound, "DataSourceLoading"));
            }

            if (this.Configuration == null)
            {
                throw new InvalidProgramException(Resources.PropertyConfigurationIsNull);
            }

            this.CreateGridView();
            this.CreatePagerSection();
            Kit.RegisterScriptBlock("GRIDVIEWPANEL_JAVASCRIPT_REGISTRATION", JAVASCRIPT_REGISTRATION);

            base.OnInit(e);
        }

        /// <summary>
        /// Raises the System.Web.UI.Control.Load event.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (this.Configuration.EnabledCheckBoxField)
            {
                foreach (GridViewRow gridViewRow in this.gridview.Rows)
                {
                    if (gridViewRow.RowType != DataControlRowType.DataRow) continue;

                    CheckBox checkBox = gridViewRow.FindControl("CheckBoxFieldItem") as CheckBox;
                    string primaryKeyFieldValue = checkBox.Attributes["PrimaryKeyFieldValue"];
                    if (string.IsNullOrEmpty(primaryKeyFieldValue)) continue;
                    if (checkBox.Checked)
                    {
                        this.CheckPrimaryKeyField(primaryKeyFieldValue);
                    }
                    else
                    {
                        this.UncheckPrimaryKeyField(primaryKeyFieldValue);
                    }
                }
            }
        }

        private void CreateGridView()
        {
            this.gridview = new WebGridView();
            this.gridview.AllowSorting = true;
            this.gridview.AutoGenerateColumns = false;
            this.gridview.AutoGenerateDeleteButton = false;
            this.gridview.AutoGenerateEditButton = false;
            this.gridview.AutoGenerateSelectButton = false;
            this.gridview.ShowHeader = true;
            this.gridview.UseAccessibleHeader = true;
            this.gridview.EmptyDataText = "";
            this.gridview.GridLines = GridLines.None;
            this.gridview.CssClass = "gridview";
            this.gridview.AlternatingRowStyle.CssClass = "alternative";
            this.gridview.RowStyle.CssClass = "item";
            this.gridview.RowCommand += (sender, arg) => { };
            this.gridview.RowEditing += (sender, arg) => { };
            this.gridview.RowDeleting += (sender, arg) => { };
            this.gridview.RowUpdating += (sender, arg) => { };
            this.gridview.RowDataBound += new GridViewRowEventHandler(this.OnGridViewDataBound);
            this.Controls.Add(this.gridview);

            this.CreateGridViewColumns();
            WebUtility.RegisterAsyncPostBackControl(this.gridview);
        }

        private void CreateGridViewColumns()
        {
            List<DataControlField> fields = new List<DataControlField>();

            // Field: Id
            TemplateField templateField = new TemplateField();
            templateField.Visible = false;
            templateField.ItemTemplate = new BoundFieldTemplate(this.Configuration.PrimaryKeyFieldName);
            fields.Add(templateField);

            // Column: CheckBox
            if (this.Configuration.EnabledCheckBoxField)
            {
                templateField = new TemplateField();
                templateField.HeaderTemplate = new FieldHeaderTemplate(this, "");
                templateField.HeaderStyle.CssClass = "gridviewheader checkbox";
                templateField.HeaderStyle.Width = new Unit("25px");
                templateField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                templateField.HeaderTemplate = new CheckBoxFieldHeaderTemplate();
                templateField.ItemStyle.CssClass = "gridviewitem";
                templateField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                templateField.ItemTemplate = new CheckBoxFieldItemTemplate(this.Configuration.PrimaryKeyFieldName);
                fields.Add(templateField);
            }

            // Configurable Fields
            foreach (GridViewFieldConfiguration bindingField in this.Configuration.Fields)
            {
                templateField = new TemplateField();
                templateField.HeaderTemplate = new FieldHeaderTemplate(this, bindingField.HeaderText);
                templateField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;

                switch (bindingField.FieldType)
                {
                    case GridViewFieldTypes.Text:
                        {
                            templateField.ItemStyle.CopyFrom(bindingField.ItemStyle);
                            templateField.ItemStyle.CssClass += " gridviewitem";
                            templateField.HeaderStyle.CopyFrom(bindingField.HeaderStyle);
                            templateField.HeaderStyle.CssClass += " gridviewheader";
                            templateField.HeaderStyle.Wrap = false;
                            if (bindingField.Sortable) templateField.SortExpression = bindingField.SortingFieldName;
                            templateField.ItemTemplate = new BoundFieldTemplate(bindingField.FieldName, bindingField.DisplayFormat, bindingField.Output)
                            {
                                ConditionalDisplayFormatter = bindingField.ConditionalDisplayFormatter
                            };
                            break;
                        }
                    case GridViewFieldTypes.UserLink:
                        {
                            templateField.ItemStyle.CopyFrom(bindingField.ItemStyle);
                            templateField.ItemStyle.CssClass += " gridviewitem";
                            templateField.HeaderStyle.CopyFrom(bindingField.HeaderStyle);
                            templateField.HeaderStyle.CssClass += " gridviewheader";
                            templateField.HeaderStyle.Wrap = false;
                            templateField.ItemTemplate = new UserLinkTemplate(bindingField.FieldName);
                            if (bindingField.Sortable) templateField.SortExpression = bindingField.SortingFieldName;
                            break;
                        }
                    case GridViewFieldTypes.OrganizationLink:
                        {
                            templateField.ItemStyle.CopyFrom(bindingField.ItemStyle);
                            templateField.ItemStyle.CssClass += " gridviewitem";
                            templateField.HeaderStyle.CopyFrom(bindingField.HeaderStyle);
                            templateField.HeaderStyle.CssClass += " gridviewheader";
                            templateField.HeaderStyle.Wrap = false;
                            templateField.ItemTemplate = new OrganizationLinkTemplate(bindingField.FieldName);
                            if (bindingField.Sortable) templateField.SortExpression = bindingField.SortingFieldName;
                            break;
                        }
                }

                fields.Add(templateField);
            }

            // Field: Buttons
            if (ShouldDisplayAnyButtons(this.Configuration))
            {
                templateField = new TemplateField();
                templateField.ItemStyle.Width = new Unit(CalculateButtonColumnWidth(this.Configuration));
                templateField.ItemStyle.CssClass = "gridviewitem center";
                templateField.HeaderText = "&nbsp;";
                templateField.HeaderStyle.CssClass = "gridviewheader";

                ButtonsTemplate buttonsTemplate = new ButtonsTemplate(this.Configuration);
                buttonsTemplate.Viewing += this.Viewing;
                buttonsTemplate.Editing += this.Editing;
                buttonsTemplate.Deleting += this.Deleting;
                buttonsTemplate.Authoritizing += this.ButtonsBinding;
                templateField.ItemTemplate = buttonsTemplate;

                fields.Add(templateField);
            }

            foreach (DataControlField dataControlField in fields)
            {
                this.gridview.Columns.Add(dataControlField);
            }
        }

        private void CreatePagerSection()
        {
            HtmlTable table = new HtmlTable() { CellPadding = 0, CellSpacing = 0, Width = "100%" };
            this.Controls.Add(table);

            HtmlTableRow row = new HtmlTableRow();
            table.Rows.Add(row);

            HtmlTableCell cell = new HtmlTableCell("td");
            row.Cells.Add(cell);
            cell.Style.Add("padding-top", "4px");
            cell.Style.Add("width", "40%");

            this.labelRecordInfo = new Label();
            cell.Controls.Add(this.labelRecordInfo);

            cell = new HtmlTableCell("td");
            row.Cells.Add(cell);
            cell.Style.Add("width", "40%");
            this.pager = new Pager() { PageSize = this.Configuration.PageSize };
            cell.Controls.Add(this.pager);

            this.pager.PageChanged += new EOffice.Components.PageChangedEventHandler(this.OnPageChanged);
        }

        private void OnPageChanged(object src, EOffice.Components.PageChangedEventArgs e)
        {
            if (this.RememberSelectedCheckBox)
                this.isPageIndexChanged = true;
            this.DataBind(this.Predicate, e.NewPageIndex - 1, this.PredicateParameters);
        }

        /// <summary>
        /// Fires when the data is bound to row.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected internal void OnGridViewDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] = "OnGirdViewRowMouseOver(this)";
                e.Row.Attributes["onmouseout"] = "OnGirdViewRowMouseOut(this)";

                if (this.Configuration.RowClickEvent != GridViewRowClickEvents.None)
                {
                    foreach (TableCell tableCell in e.Row.Cells)
                        if (tableCell.Attributes["AllowCellClickable"] != "false")
                            tableCell.Attributes["onclick"] = string.Format("OnGridViewRowClicked(this, \"{0}\")", this.Configuration.RowClickEvent);
                }

                CheckBox checkBoxFieldItem = e.Row.FindControl("CheckBoxFieldItem") as CheckBox;
                if (checkBoxFieldItem != null)
                    checkBoxFieldItem.Checked = this.CheckedPrimaryKeyFieldValues.Contains(checkBoxFieldItem.Attributes["PrimaryKeyFieldValue"]);

                if (this.CheckBoxBinding != null && checkBoxFieldItem != null)
                    this.CheckBoxBinding(this, new GridViewCheckBoxBindingEventArgs(e.Row.DataItem, checkBoxFieldItem));
            }
        }

        /// <summary>
        /// Fires when the gridview is sorting.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected internal void OnGridViewSorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = string.Format("{0} {1}", e.SortExpression, e.SortDirection == SortDirection.Ascending ? "ASC" : "DESC");
            if (this.SortExpression == sortExpression)
            {
                this.SortExpression = string.Format("{0} {1}", e.SortExpression, e.SortDirection == SortDirection.Ascending ? "DESC" : "ASC");
            }
            else
            {
                this.SortExpression = sortExpression;
            }

            this.DataBind(this.Predicate, this.pager.CurrentPageIndex - 1, this.PredicateParameters);
        }

        #region DataBind Methods

        /// <summary>
        /// Data bind to gridview on event DataSourceLoading with current page index.
        /// </summary>
        public override void DataBind()
        {
            this.DataBind(this.Predicate, this.pager.CurrentPageIndex - 1, this.PredicateParameters);
        }

        /// <summary>
        /// Data bind to gridview on event DataSourceLoading with specified page index.
        /// </summary>
        /// <param name="pageIndex"></param>
        public void DataBind(int pageIndex)
        {
            this.DataBind(this.Predicate, pageIndex, this.PredicateParameters);
        }

        /// <summary>
        /// Data binding to gridview on event DataSourceLoading with current page index.
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="parameters"></param>
        public void DataBind(string predicate, params object[] parameters)
        {
            this.DataBind(predicate, this.pager.CurrentPageIndex - 1, parameters);
        }

        /// <summary>
        /// Data bind to gridview replies on event DataSourceLoading.
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="pageIndex"></param>
        /// <param name="parameters"></param>
        public void DataBind(string predicate, int pageIndex, params object[] parameters)
        {
            this.DataBind(null, predicate, pageIndex, parameters);
        }

        /// <summary>
        /// Data bind to gridview replies on event DataSourceLoading.
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="criterias"></param>
        public void DataBind(int pageIndex, IEnumerable<QueryCriteria> criterias)
        {
            this.DataBind(criterias, null, pageIndex, null);
        }

        /// <summary>
        /// Data bind to gridview replies on event DataSourceLoading.
        /// </summary>
        /// <param name="criterias"></param>
        /// <param name="predicate"></param>
        /// <param name="pageIndex"></param>
        /// <param name="parameters"></param>
        public void DataBind(IEnumerable<QueryCriteria> criterias, string predicate, int pageIndex, params object[] parameters)
        {
            if (!this.isPageIndexChanged)
                this.UncheckAllPrimaryKeyFields();

            if (this.DataSourceLoading != null)
            {
                if (criterias != null)
                    this.Criterias = new Collection<QueryCriteria>(criterias.ToList());

                this.Predicate = predicate;
                this.PredicateParameters = parameters;

                DataSourceLoadEventArgs e = new DataSourceLoadEventArgs(criterias, predicate, pageIndex, this.pager.PageSize, this.SortExpression, parameters);
                this.DataSourceLoading(this, e);

                if (e.RecordCount > 0) this.gridview.DataSource = e.DataSource;
                else this.gridview.DataSource = this.CreateEmptyData();

                this.gridview.DataBind();

                this.pager.CurrentPageIndex = pageIndex + 1;
                this.pager.RecordCount = e.RecordCount;
                this.pager.DataBind();

				this.labelRecordInfo.Text = string.Format(Resources.GridViewPagerSummaryTemplate, new object[] { this.Configuration.EntityName, e.RecordCount, pager.PageCount, pager.CurrentPageIndex, pager.PageSize });
                SessionManager.Current.SetSession(CURRENT_PAGE_INDEX, pageIndex);
            }
        }

        #endregion

        /// <summary>
        /// Add checked primary key field value. 
        /// The checkbox in the row with the matched value will be checked automatically.
        /// </summary>
        /// <param name="primaryKeyFieldValue"></param>
        public void CheckPrimaryKeyField(string primaryKeyFieldValue)
        {
            Kit.NotNull(primaryKeyFieldValue, "primaryKeyFieldValue");

            if (!this.CheckedPrimaryKeyFieldValues.Contains(primaryKeyFieldValue))
                this.CheckedPrimaryKeyFieldValues.Add(primaryKeyFieldValue);
        }

        /// <summary>
        /// Remove all checked primary key field values.
        /// </summary>
        public void UncheckAllPrimaryKeyFields()
        {
            this.CheckedPrimaryKeyFieldValues.Clear();
        }

        /// <summary>
        /// Remove checked primary key field value.
        /// </summary>
        /// <param name="primaryKeyFieldValue"></param>
        public void UncheckPrimaryKeyField(string primaryKeyFieldValue)
        {
            //Kit.NotNull(primaryKeyFieldValue, "primaryKeyFieldValue");

            if (this.CheckedPrimaryKeyFieldValues.Contains(primaryKeyFieldValue))
                this.CheckedPrimaryKeyFieldValues.Remove(primaryKeyFieldValue);
        }

        private DataTable CreateEmptyData()
        {
            DataTable dt = new DataTable(this.Configuration.EntityName);
            dt.Columns.Add(this.Configuration.PrimaryKeyFieldName);

            foreach (GridViewFieldConfiguration bindingField in this.Configuration.Fields)
            {
                string[] fieldNames = bindingField.FieldName.Split(';');
                foreach (string fieldName in fieldNames)
                {
                    if (!dt.Columns.Contains(fieldName.Trim()))
                    {
                        dt.Columns.Add(fieldName.Trim());
                    }
                }
            }

            dt.Rows.Add(dt.NewRow());
            dt.AcceptChanges();

            return dt;
        }

        private static string CalculateButtonColumnWidth(GridViewConfiguration gridViewConfiguration)
        {
            int width = 0;
            if (gridViewConfiguration.ViewButton != null) width += 20;
            if (gridViewConfiguration.EditButton != null) width += 20;
            if (gridViewConfiguration.DeleteButton != null) width += 20;

            return string.Format("{0}px", width);
        }

        private string GetSortExpressionSessionKey()
        {
            string sessionKey = SessionManager.ObjectId;
            if (string.IsNullOrEmpty(sessionKey))
            {
                sessionKey = string.Format("{0}::{1}::{2}::SortExpression", HttpContext.Current.Request.Url, HttpContext.Current.Handler.GetType(), this.ID);
            }
            else
            {
                sessionKey = string.Format("{0}::{1}", sessionKey, this.ID);
            }

            return sessionKey;
        }

        /// <summary>
        /// Returns true if there has any buttons configured to be displayed in column.
        /// </summary>
        /// <param name="gridViewConfiguration"></param>
        private static bool ShouldDisplayAnyButtons(GridViewConfiguration gridViewConfiguration)
        {
            if (gridViewConfiguration.DeleteButton != null || gridViewConfiguration.EditButton != null || gridViewConfiguration.ViewButton != null)
            {
                return true;
            }

            return false;
        }
    }
}
